import { useContext, useEffect, useRef, useState } from 'react';
import { ContractCountContext } from '../common';
import { Badge, Col, Empty, Row } from 'antd';
import ScrollBarLayout from '@/components/ScrollBarLayout';
//引入echarts主模块
import * as echarts from 'echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入饼状图
import 'echarts/lib/chart/pie';
// 引入标题和提示框
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import ReactDOM from 'react-dom';
import { handleSum, handleSumStr, summation } from '../mconfig';

/** 合同数量 */
let contractNum: any;

/** 合同金额 */
let contractSum: any;

/** 合同金额数量明细 */
let contractNumSum: any;

export const AllCountEhcartsView: React.FC<ContractAllCountAPI.IAllCountEhcartsView> = () => {
  /** 引入上下文 */
  const { echartsDetailInfo, styleFixCls, stepTypeValue } = useContext(ContractCountContext);

  /**  合同数量汇总统计  */
  let contractCountRef: any = useRef();

  /** 合同金额汇总统计 */
  let contractSumRef: any = useRef();

  /** 合同数量金额汇总统计 */
  let contractAllRef: any = useRef();

  /** 合同数量总值 */
  let [contractAllNum, setContractAllNum] = useState<number>(0);

  /** 合同金额总值 */
  let [contractAllPrice, setContractAllPrice] = useState<number>(0);

  /** 合并统计对象values值 */
  const mergeObjValue = (objInfo: Record<string, any>, countType?: boolean) => {
    let contractDataList: Record<string, any>[] = []; //饼图数量金额
    // let contractLegendList: string[] = []; //饼图数量金额

    let putAwayBarNum: number[] = []; // 明细收款数量
    let putAwayBarSum: number[] = []; // 明细收款金额
    let payBarNum: number[] = []; //明细付款数量
    let payBarSum: number[] = []; //明细付款金额
    let notBarNum: number[] = []; //明细无金额数量
    let notBarSum: number[] = []; //明细无金额金额

    Object?.keys(objInfo)?.forEach((item: any) => {
      let a_putAwayBarNum: number = 0;
      let a_putAwayBarSum: number = 0;
      let b_payBarNum: number = 0;
      let b_payBarSum: number = 0;
      let c_notBarNum: number = 0;
      let c_notBarSum: number = 0;

      objInfo[item]?.forEach((itemValue: any) => {
        // let pieName: string = ""
        let pieNameStr: string = '';
        if (itemValue?.capitalDir == 0) {
          pieNameStr = '付款';

          b_payBarNum += itemValue?.totalNum;
          b_payBarSum += itemValue?.totalSum;

          payBarNum?.push(b_payBarNum);
          payBarSum?.push(b_payBarSum);
        } else if (itemValue?.capitalDir == 1) {
          pieNameStr = '收款';

          a_putAwayBarNum += itemValue?.totalNum;
          a_putAwayBarSum += itemValue?.totalSum;

          putAwayBarNum?.push(a_putAwayBarNum);
          putAwayBarSum?.push(a_putAwayBarSum);
        } else if (itemValue?.capitalDir == 2) {
          pieNameStr = '无金额';

          c_notBarNum += itemValue?.totalNum;
          c_notBarSum += itemValue?.totalSum;

          notBarNum?.push(c_notBarNum);
          notBarSum?.push(c_notBarSum);
        }

        const newItem: any = {
          value: countType ? itemValue?.totalNum : Number(itemValue?.totalSum),
          name: pieNameStr,
        };
        contractDataList?.push(newItem);
        // contractLegendList?.push(pieNameStr);
      });
    });

    return {
      contractDataList,
      // contractLegendList,
      putAwayBarNum,
      putAwayBarSum,
      payBarNum,
      payBarSum,
      notBarNum,
      notBarSum,
      numSumKeys: Object?.keys(objInfo),
    };
  };

  /** 处理合并饼图 */
  const handleMerginPieData = (pieDataList: Record<string, any>) => {
    let allSumNumInfo: Record<string, any> = {};
    pieDataList?.forEach((itemInfo: any) => {
      let sumNumValue: number = allSumNumInfo?.[itemInfo?.name]?.value ? allSumNumInfo?.[itemInfo?.name]?.value : 0;
      sumNumValue += itemInfo?.value;
      allSumNumInfo[itemInfo?.name] = {
        name: itemInfo?.name,
        value: sumNumValue,
      };
    });

    return {
      pieLegendKeys: Object?.keys(allSumNumInfo),
      pieDataValues: Object?.values(allSumNumInfo),
    };
  };

  /** 初始化 */
  useEffect(() => {
    if (echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}') {
      contractCountPie(echartsDetailInfo, true);
      contractCountPie(echartsDetailInfo, false);
      contractCountBar(echartsDetailInfo);
    } else {
      setContractAllNum(0);
      setContractAllPrice(0);
    }
  }, [echartsDetailInfo]);

  /** 合同数量金额饼状图统计 */
  const contractCountPie = (dataInfo: Record<string, any>, pieType: boolean) => {
    if (pieType) {
      if (contractNum != null && contractNum != '' && contractNum != undefined) {
        contractNum?.dispose();
      }
    } else {
      if (contractSum != null && contractSum != '' && contractSum != undefined) {
        contractSum?.dispose();
      }
    }

    const { contractDataList } = mergeObjValue(dataInfo, pieType);

    const { pieLegendKeys, pieDataValues } = handleMerginPieData(contractDataList);
    const computeNum = summation(pieDataValues); //求和

    if (pieType) {
      setContractAllNum(computeNum);
    } else {
      setContractAllPrice(computeNum);
    }

    const colorNum = ['#59d6a5', '#fcc128', '#5c6191'];
    const colorSum = ['#2d92c7', '#e17ec7', '#6d6a6a'];

    const option: Record<string, any> = {
      title: {
        text: `合同${pieType ? '数量' : '金额'}汇总统计`,
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        // formatter: `{b} : {c}${pieType ? '个' : '元'}（{d}%）`,
        formatter: (params) => {
          if (pieType) {
            return `${params?.name}<br />${params?.marker}数量：${params?.value}个`;
          } else {
            return `${params?.name}<br />${params?.marker}金额：${handleSumStr(params?.value)}`;
          }
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['收款', '付款'],
        padding: [25, 5],
      },
      color: pieType ? colorNum : colorSum,
      series: [
        {
          type: 'pie',
          radius: '50%',
          // data: contractDataList,
          data: pieDataValues,
          label: {
            formatter: `{b} : {c}${pieType ? '个' : '元'}（{d}%）`,
          },
        },
      ],
    };

    if (pieType) {
      /** 合同数量汇总 */
      const contractNumDiv: any = ReactDOM.findDOMNode(contractCountRef?.current);
      contractNum = echarts.init(contractNumDiv);
      contractNum.setOption(option, true);
    } else {
      /** 合同金额汇总 */
      const contractSumDiv: any = ReactDOM.findDOMNode(contractSumRef?.current);
      contractSum = echarts.init(contractSumDiv);
      contractSum.setOption(option, true);
    }
  };

  /**
   * 处理柱状图鼠标移入气泡
   * @param params
   * @returns
   */
  const renderTooltip = (params: Record<string, any>[]) => {
    let tipStr: string = `${params?.[0]?.name}`;
    params?.forEach((item: any) => {
      tipStr += ` 
          <br />
          ${item?.marker}${item?.seriesName}：${item?.seriesName?.includes('数量') ? item?.value + ' 个' : handleSumStr(Number(item?.value))
        }
          `;
    });
    return tipStr;
  };

  /** 合同数量金额柱状图 */
  const contractCountBar = (dataInfo: Record<string, any>) => {
    if (contractNumSum != null && contractNumSum != '' && contractNumSum != undefined) {
      contractNumSum?.dispose();
    }

    const { putAwayBarNum, putAwayBarSum, payBarNum, payBarSum, numSumKeys } = mergeObjValue(dataInfo);

    const option = {
      title: {
        text: '合同数量金额明细统计',
        left: 'center',
      },
      grid: {
        left: '10%',
        bottom: '10%',
        top: '25%',
        right: '10%',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params) => {
          return renderTooltip(params);
        },
      },
      legend: {
        data: ['付款数量', '收款数量', '付款金额', '收款金额'],
        padding: [30, 5],
      },
      toolbox: {
        show: true,
        feature: {
          magicType: {
            mark: { show: true },
            show: true,
            type: ['line', 'bar'],
            title: {
              line: '',
              bar: '',
            },
          },
        },
        right: '5%',
        padding: [30, 5],
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          data: numSumKeys,
          // name: stepTypeValue,
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '数量/个',
          position: 'left',
          alignTicks: true,
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: (value) => {
              return Number.isInteger(value) ? value : '';
            },
          },
        },
        {
          type: 'value',
          name: '金额/元',
          position: 'right',
          alignTicks: true,
          axisLine: {
            show: true,
          },
        },
      ],
      // color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622'],
      series: [
        {
          name: '付款数量',
          type: 'bar',
          data: payBarNum,
          yAxisIndex: 0,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '收款数量',
          type: 'bar',
          data: putAwayBarNum,
          yAxisIndex: 0,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '付款金额',
          type: 'bar',
          data: payBarSum,
          yAxisIndex: 1,
          label: {
            show: true,
            position: 'top',
          },
        },
        {
          name: '收款金额',
          type: 'bar',
          data: putAwayBarSum,
          yAxisIndex: 1,
          label: {
            show: true,
            position: 'top',
          },
        },
      ],
    };

    /** 合同数量汇总 */
    const contractNumSumDiv: any = ReactDOM.findDOMNode(contractAllRef?.current);
    contractNumSum = echarts.init(contractNumSumDiv);
    contractNumSum.setOption(option, true);
  };

  /** 返回徽标 */
  const renderBadgeText = () => {
    return (
      <span>
        <div>
          <span>
            总数量：
            <span style={{ fontSize: 16, color: '#ff4d4f', fontWeight: 600 }}>{contractAllNum || 0}</span>
            &nbsp;个
          </span>
        </div>
        <div>
          <span>
            总金额：
            {handleSum(contractAllPrice)}
          </span>
        </div>
      </span>
    );
  };

  return (
    <div className={`${styleFixCls}allCountDiv-bodyBox`}>
      <ScrollBarLayout style={{ padding: '0px' }}>
        <Row>
          <Col span={12} style={{ paddingRight: 2 }}>
            <Badge.Ribbon text={renderBadgeText()} color="#ececec" className={`${styleFixCls}allCountDiv-bodyBox-BadgeDiv`}>
              <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
                {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                  <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={contractCountRef} />
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同数量汇总统计】数据" />
                )}
              </div>
            </Badge.Ribbon>
          </Col>
          <Col span={12} style={{ paddingLeft: 2 }}>
            <Badge.Ribbon text={renderBadgeText()} color="#ececec" className={`${styleFixCls}allCountDiv-bodyBox-BadgeDiv`}>
              <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
                {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                  <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={contractSumRef} />
                ) : (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同金额汇总统计】数据" />
                )}
              </div>
            </Badge.Ribbon>
          </Col>
          <Col span={24} style={{ paddingTop: 4 }}>
            <div className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
              {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={contractAllRef} />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同数量金额明细统计】数据" />
              )}
            </div>
          </Col>
        </Row>
      </ScrollBarLayout>
    </div>
  );
};
